<?php
namespace app\index\controller;

use app\common\controller\Common;
use org\ChapterPage;
use think\facade\Cache;
use think\facade\Config;

class Chapter extends Common
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function index($article_id = 0,$chapter_id = 0)
    {
        //章节分页
        $chapter_ids = explode("_",$chapter_id);
        $page = 1;
        if (count($chapter_ids) > 1) {
            $chapter_id = $chapter_ids[0];
            $page = $chapter_ids[1];
        }
        //请求小说信息
        $article = curl_server("apiv2/article?id=" . $article_id);
        $article = $article['data'];
        $chapter_flag = "";
        if (is_array($article) && array_key_exists("chapter_list",$article)) {
            if (count($article['chapter_list']) > 0) {
                $chapter_flag = $article['chapter_list'][0]['flag'];
            }
        }
        $result2 = curl_server(sprintf("apiv2/chapter?article_id=%d&chapter_id=%d&flag=%s",$article_id,$chapter_id,$chapter_flag));
        $chapter = $result2['data'];

        //替换div为空
        $chapter['content'] = preg_replace('/<\/*div.*?>/u',"",$chapter['content']);

        //章节分页
        $showPage = "";
        $chapter_page_size = 500;
        if (!empty($this->site_config['extend']['chapter_page_content_num'])) {
            $chapter_page_size = $this->site_config['extend']['chapter_page_content_num'];
        }
        if ($this->site_config['extend']['chapter_page_content_switch'] == 'on') {
            $cp = new ChapterPage(sprintf("chapter/%d/%d_{PAGE}",$article_id,$chapter_id),$chapter['content'],$page,$chapter_page_size);
            $pages = $cp->cutStr();
            if (count($pages) > 0 && $page <= count($pages)) {
                $chapter['content'] = $pages[$page - 1];

                if (isMobileDomain()) {
                    $showPage = $cp->showHs13PrvNext2();
                }else {
                    $showPage = $cp->pageNav();
                }

            }
        }

        $prev = "";
        $next = "";

        //章节上下页面
        if (!empty($article['chapter_list'])) {
            foreach ($article['chapter_list'] as $key => $item) {
                if ($item['id'] == $chapter_id) {
                    if ($key - 1  >= 0) {
                        $prev = $article['chapter_list'][$key - 1];
                    }
                    if ($key + 1  < count($article['chapter_list'])) {
                        $next = $article['chapter_list'][$key + 1];
                    }
                    continue;
                }
            }
        }

        $this->site_seo('chapter',array('chapter' => $chapter,'article' => $article,'category_name' => show_cid_name($article['cid'])));
        $this->assign("showPage",$showPage);


        return $this->fetch("index",["article" => $article,"chapter" => $chapter,"prev" => $prev,"next" => $next]);
    }

}

